
{include file="common/head"}
<head>
	<script src="/static/flatpickr/flatpickr.min.js"></script>
	<link rel="stylesheet" href="/static/flatpickr/flatpickr.min.css"> 
	<style>
		.section{background-color: #fff;border-radius: 10px;padding:10px;margin: 10px 0;box-shadow: 0 0 2px #666;}
		.cat_info{margin: 5px;display:none;border: 0 solid #ccc;text-align: center;}
		.cat_selected{background: #007bff;border-color: #007bff;color: white;}
		.address{padding:5px 10px;}
		#price,#km{font-size: 26px;}
		.row div{padding: 0;}
		#top{background: #f60;border-bottom: 1px solid #ccc;z-index: 21;}
		#bottom{background: #f60;color: white;z-index: 21;}
		a{color: white;text-decoration: none;}
		.add_check{display:none;color: #f60;font-size: 2rem;}
	</style>	
</head>

<body style="background-imagex: linear-gradient(to bottom,#f60, #fff);background: #f60;">
	<div class="container-fluid" style="max-width: 800px;margin:0 auto;">
	
	<!-- 标题 -->
	<div id="top" class="row" class="text-center" style="color:white;">
		<div class="col text-center" style="padding: 0;">
			<span class="">{$sys.sys_name}</span>
			<span class="bi-geo-alt-fill text-secondary" id="init_city" >广州市</span>

		</div>
		

	</div>

	<div style="height:55px;"></div>

	<div id="content" style="background-color:#ccc;border-radius:10px;min-height: 500px;">

		<div class="section" style="background: initial;">
			<div class="cat_list">
			{foreach $cat as $k=>$c}
				{if $c['deepth']==2}
					<button class="btn btn-sm btn-outline-primary btn-cat" cat="{$k}">{$c['name']}</button>
				{/if}
			{/foreach}
			</div>

			{foreach $cat as $k=>$c}
				{if $c['deepth']==2}		
					<div class="cat_info" cat="{$k}">
						<img src="{$c['img']}" style="border-radius: 10px;min-width:150px;max-width: 80%;min-height:80px;max-height: 100px;margin:10px auto;" lat="No image" />
						<div class="text-primary">{$c['title']}</div>

						<div class="row">
							<div class="col">起步距离(km):<span class="text-primary base_distance">{$c['base_distance']}</span></div>
							<div class="col">起步价($):<span class="text-primary base_price">{$c['base_price']}</span></div>
							<div class="col">公里价格($):<span class="text-primary price_per_km">{$c['price_per_km']}</span></div>

						</div>
					</div>


				{/if}
			{/foreach}
		</div>

		<!-- 地址选择 -->
		<div class="section"  style="">
			<div class="row address" > 
				<div class="col-2" id="from">
					<span class="bi-geo-alt-fill"></span>装货
					<input type="text" id="pos1" style="display: none;"/>
				</div>
				<div class="col-9"  id="address1" style="word-break: break-all;border-bottom: 1px solid #ccc;">
				</div>
				<div class="col-1 text-center"><span class="bi-book-half" id="book1" ></span></div>
			</div>

			<div class="row address"  >
				<div class="col-2" id="to">

					<span class="bi-geo-alt-fill"></span>卸货
					<input type="text" id="pos2" style="display: none;" />
				</div>
				<div class="col-9" id="address2" style="word-break: break-all;border-bottom: 1px solid #ccc;">
				</div>
				<div class="col-1 text-center"><span class="bi-book-half" id="book2"></span></div>	
			</div>	

			<div class="row address" >
				<div class="col-4" id="create_time">用车时间：</div>
			  <div class="col-6 text-left" >
				<input class="form-control" type="text" value="" id="want_time" name="want_time" placeholder="预计出发时间" />
			  </div>	

			</div>
		</div>

		<!--地址编辑框-->
		<div id="addr_editor" style="display: none;position: fixed;z-index: 22;background: #fff;left:15px;right:15px;top:240px;border:1px solid #ccc;min-height: 300px;border-radius: 5px;padding:15px;">
			<div class="row">
				<div class="col-2"></div>
				<div class="col-8 text-primary text-center">地址编辑(Address edit)</div>
				<div class="col-2 text-center"><span class="bi-x-lg" id="edit_close"></span></div>
			</div>
			<div><input id="addr_id" value="" type="hidden" readonly /></div>
			<div>地址(Address)</div>
			<div>
					<textarea class="form-control" id="addr_text" value=""></textarea>
			</div>
			<div>收货人(Name)</div>
			<div>
					<input type="text" class="form-control" id="addr_cont" value="" />
			</div>
			<div>收货人电话(Mobile/Tel)</div>
			<div>
				<input type="text" class="form-control" id="addr_mobile" value="" />
			</div>
			<br/>
			<div>
				<button type="button" class="form-control btn btn-primary" id="addr_save">
				<span class="bi-check">确定(Ok)</span>
				</button>
				<button type="button" class="form-control btn btn-info" id="addr_save_book" style="margin-top:10px;">
				<span class="bi-book-half">存地址簿(Save to address book)</span>
				</button>				
			</div>
				
		</div>		

		<!-- 下单 -->
		<div class="section" style="margin: 10px 0;" >		
			<div class="text-center">
				车型：<span id="cat_name" style="font-size: 1.2rem;font-weight: bold;"></span>,
				距离：<span id="km">0</span>km,
				价格：$<span id="price">0.00</span>
			</div>
			<br/>

			<div class="text-center">
			  <div class="btn-group">
			    <button id="place_order" type="button" class="btn btn-primary" style="padding:3px 30px;">下单</button>
			    <!-- <button id="booking_order" type="button" class="btn btn-info" style="padding:5px 30px;">预约</button> -->
			  </div>
		  
			</div>

			<br/>
		</div>

		<!--其他链接 -->
		<div class="section" style="">
			<div class="row">
				<div class="col text-center" >
					<a href="/index.php/customer/address_man" style="color:#555;">
						<span class="bi-book" style="font-size: 1.2rem;"></span><br/>地址簿
					</a>
				</div>

						
				<div class="col text-center">
					<input type="hidden" id="is_driver" value="{$truck['cat']}" />
					{if $truck['cat']>0}
					<a href="/index.php/truck/edit/view/_mobile" style="color:#555;">
						<span class="bi-truck" style="font-size: 1.2rem;"></span><br/>我的货车
					</a>
					{else}
					<a href="/index.php/truck/truck_add/view/_mobile" style="color:#555;">
						<span class="bi-truck" style="font-size: 1.2rem;"></span><br/>司机加入
					</a>
					{/if}
				</div>
				<div class="col"></div>	
				<div class="col text-center" id="trucks_near" style="color:#555;">
					<span class="bi-truck-flatbed" style="font-size: 1.2rem;"></span><br/>附近货车
				</div>				
			</div>
		</div>

		<div class="section" style="height:50px;margin-bottom: 50px;">
			<div class="text-center"> </div>
		</div>

		<div  style="height:50px;"></div>
			

	</div>

	<!--地图层 -->
	<div id="container" style="display: none;position: fixed;top: 0px;left:0px;right:0px;bottom:84px;z-index: 22;background: #fff;">

		<div id="googleMap" style="width:100%;height:100%;"></div>

		<div class="row" style="margin:0px;" >
			<div class="input-group">
				<input id="address_input" type="text" class="form-control" placeholder="小提示：多利用【附近地址】，快速选择。" style="font-weight: bold;color:#00f;border-radius:0;" />
				<button id="address_search" class="input-group-text bi-search btn btn-secondary">查找</button>
				<button id="address_get" class="input-group-text bi-check-lg btn btn-primary" style="border-radius: 0;">确定</button>

			</div>
		</div>

	</div>

	<!--地址选择本-->
	<div id="address_list" class="section" style="display: none;position: fixed;left:10px;right:10px;bottom:50px;top: 100px;z-index: 20;border:1px solid #555;overflow-y: scroll;">
		<div id="addresses">
		</div>
		<div>11</div>
	</div>

	<div id="mask">mask layer</div>
	
	<!-- 地址模板 -->
	<div id="add_module" style="display: none;">
		<div class="row address" style="border-top: 1px solid #ccc;">
			<div class="col-10">
			<div class="addr text-primary">[addr]</div>
				<div class="text-info">
					<span class="cont text-info">[cont]</span>
					<span class="mobi text-info">[mobi]</span>
				</div>
				<span class="bi-geo-alt-fill"></span><span class="pos text-info">[pos]</span>
			</div>
			<div class="col-2 text-right">
				<span class="add_check bi-check-circle"></span>
			</div>
		</div>
	</div>

	<input type="hidden" value="{$sys.msg}" id="show_msg" />
	<input type="hidden" value="{$sys.pwd_msg}" id="pwd_msg"/>

	<!-- 底部栏 -->
 	{include file="common/bottom"}

	<div style="height: 50px;"></div>
	</div>



<style>
	.custom-map-control-button{margin:20px 2px;padding: 3px 8px;border-radius: 12px;border-width: 1px;box-shadow: 0 0 2px #f00;}
	.near_address{cursor: pointer;background-color:#fff;border-radius: 4px;margin-bottom: 2px;padding: 0 4px;}
</style>


<script type="text/javascript">

	// google.maps.MapTypeId.HYBRID      ：显示卫星图像的主要街道透明层
	// google.maps.MapTypeId.ROADMAP      ：显示普通的街道地图
	// google.maps.MapTypeId.SATELLITE    ：显示卫星图像


	//附近地点数组
	var nearby=[];
	
	//路线数据
	var route_obj={
		address_start:'',
		address_end:'',
		distance: 0,
		duration:''
	};
	var current_pos='';

	var base_distance=0;
	var distance=0;
	var base_price=0;
	var price_per_km=0;


	//加载地图资源
	function loadScript(){
	  var script = document.createElement("script");
	  script.type = "text/javascript";
	  script.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyB6GHAYtKuxzrTKcbwi6VWg65TmOuI5608&libraries=places&sensor=true&callback=initialize";
	  document.body.appendChild(script);
	}
	var outTextQuery=null;
	var outCalcRoute=null;
	var a_find=0;

	//地图初始化函数，定义地图中心，属性，类型等
	function initialize(){
		var infoWindow;
		var center=new google.maps.LatLng(11.569593, 104.920915);

		
		//地图属性
		var mapProp = {
			center: center,
			zoom:15,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
			panControl:false,
			zoomControl:true,
			mapTypeControl:false,
			scaleControl:true,
			streetViewControl:false,
			overviewMapControl:true,
			rotateControl:false
		};

		//地图建立
		var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);


		//路线服务与渲染
		var directionsService = new google.maps.DirectionsService();
		var directionsRenderer = new google.maps.DirectionsRenderer();				
		directionsRenderer.setMap(map);
	

		//一个信息窗口
		// var infowindow = new google.maps.InfoWindow({
		// 	content:"我们在这里!"
		// });
		// infowindow.open(map,marker);


		//地理定位到当前位置,需要准备一些东西//////////////////////////////////////////////////
		infoWindow = new google.maps.InfoWindow({content:'Location found!'});
		const locationButton = document.createElement("button");
		const nearbyButton = document.createElement("button");
		const closeMapButton = document.createElement("button");
		const calcRouteButton = document.createElement("button");


		//addtional buttons 
		locationButton.textContent = "当前位置";
		nearbyButton.textContent = "附近地址";
		calcRouteButton.textContent = "路线规划";
		closeMapButton.textContent = "退出(Exit)";

		locationButton.classList.add("custom-map-control-button");
		nearbyButton.classList.add("custom-map-control-button");
		calcRouteButton.classList.add("custom-map-control-button");
		closeMapButton.classList.add("custom-map-control-button");

		map.controls[google.maps.ControlPosition.BOTTOM].push(locationButton);
		map.controls[google.maps.ControlPosition.BOTTOM].push(nearbyButton);
		map.controls[google.maps.ControlPosition.BOTTOM].push(calcRouteButton);
		map.controls[google.maps.ControlPosition.BOTTOM].push(closeMapButton);


		locationButton.addEventListener("click",whereIsHere);
		//找出当前的定位
		function whereIsHere(){
			// Try HTML5 geolocation.
			if (navigator.geolocation) {
				navigator.geolocation.getCurrentPosition(
				  success=>{

				  	//console.log(success);
					const pos = {
						lat: success.coords.latitude,
						lng: success.coords.longitude,
					};

					//显示位置信息
					setMarker(pos,'');
					map.panTo(pos);
					//setTimeout(function(){setInfo(pos,"let's go!!!!!!!!!!!!!",map);},2000)
					center =  pos;
					current_pos = pos;
					find_city(pos);

				}
				,function(error){alert(error.message);}//定位出错的信息显示
				,{
				 //可增加的4个配置参数
				  enableHighAccuracy:true,//高精度
				  timeout:5000,//超时时间,以ms为单位
				  maximumAge:24*60*60*1000,//位置缓存时间,以ms为单位
				}
				);
			} else {
				alert("Browser doesn't support Geolocation");

			}
		}

		////定位当前位置////////////////////////////////////////////////// 		

		//清除markers
		function cleanMarkers(){
			console.log('There are '+markers.length+' markers,now clean markers...');

			for(i in markers){
				markers[i].setMap(null);
				markers[i]=null;
			}
			markers.length=0;
			console.log('There are '+markers.length+" markers");


			for(i in circles){
				circles[i].setMap(null);
			}
			circles.length=0;

		}

		//退出地图
		closeMapButton.addEventListener('click',function(){
			document.getElementById('container').style.display='none';
			document.getElementById('mask').style.display='none';
		});



		//文本搜索地址
		function textQuery(place){
		  if(!place.trim()) {
		  	layer.open({content:'请输入你要搜索的地址关键字!'});return;
		  }
		  var request = {
		    query: place,
		    fields: ['name', 'geometry'],
		  };

		  var service = new google.maps.places.PlacesService(map);

		  service.findPlaceFromQuery(request, function(results, status) {
		    if (status === google.maps.places.PlacesServiceStatus.OK) {
		      //for (var i = 0; i < results.length; i++) {
		      setMarker(results[0].geometry.location,'');
		      //}
		      map.panTo(results[0].geometry.location);
		      center = results[0].geometry.location;
		      find_city(center);
		    }
		  });
		}

		//draw with a circel
		var circles=[];
		function drawCircle(pos,radius){
			for(i in circles){
				circles[i].setMap(null);
			}
			circles.length=0;

		    var circle = new google.maps.Circle({
		      strokeColor: "#FF6600",
		      strokeOpacity: 0.5,
		      strokeWeight: 1,
		      fillColor: "#0000ff",
		      fillOpacity: 0.1,
		      map,
		      center: center,
		      radius:radius 
		    });
		    circles.push(circle);
		}


		/*--------------------------------------------------------------
		地图监听事件,在点击的位置创建标记
		如果有placeId,取得他的资料
		*/
		map.addListener("click",mapClick);
		function mapClick(e){
			console.log({'Map click':JSON.stringify(e.latLng)});
			map.panTo(e.latLng);
			center = e.latLng;

			find_city(center);

			//get infomation of the marker is clicked.
			if(e.placeId){
				var service = new google.maps.places.PlacesService(map);	
				var request = {
					placeId:e.placeId
				};				
				service.getDetails(request,function(result,status){
					if(status=='OK'){
						console.log({status:status,result:result});
						//setMarker(e.latLng,'O',e.placeId);
						document.getElementById('address_input').value="【"+result.name+"】"+result.formatted_address;
						document.getElementById('pos'+a_find).value=JSON.stringify(result.geometry.location);

						if(a_find==2 && confirm("是否选择这个地址?")){
							calcRoute();
						}
					}else{
						alert('From google:['+status+']');
					}
					

				});
			}else{
				//set a new marker when no any placeId found.
				document.getElementById('pos'+a_find).value=JSON.stringify(center);
				cleanMarkers();
				setMarker(e.latLng);
			}
		}
		//------------------------------------------------------------------

		
		//做标记，标记内容，信息窗
		var markers=[]; //标记数组
		var trucks=[]; //标记数组
		function setMarker(pos,txt='',placeId='',icon=''){
			//console.log({'set marker at pos':pos,'placeId':placeId});
			var marker=new google.maps.Marker({
				position:pos,
				map,
				icon:icon,
				//animation:google.maps.Animation.BOUNCE //一动一动的图标
			});

			if(txt) {marker.setLabel(txt+'');}
			markers.push(marker);

			
			//做自己的标记
			if(placeId){
				google.maps.event.addListener(marker, 'click', function() {
					console.log('Marker on placeId:'+placeId);

					//查出图标的详细资料
					var service = new google.maps.places.PlacesService(map);	
					var request = {placeId:placeId};

					service.getDetails(request,function(result,status){
						if(status=='OK'){
							console.log({'place detail':{status:status,result:result}});
							var infoTxt = "<div style='font-weight:bold;color:blue;'>"+result.name+"</div><div>"+result.formatted_address+"</div>";
								infoTxt+="<div style='border-top:1px solid #ccc;'><a style='color:blue;' href='"+result.url+"' target='_blank'>Google for this place</a></div>";
							setInfo(pos,infoTxt,map);
							
							document.getElementById('address_input').value="【"+result.name+"】"+result.formatted_address;
							document.getElementById('pos'+a_find).value=JSON.stringify(result.geometry.location);

							calcRoute();

						}else{
							alert('From google:['+status+']');
						}

					});


				});
			}

			//marker.setMap(map); 
		}


		//附近搜索
		nearbyButton.addEventListener("click",nsearch);
		function nsearch(){
			var request = {
				location: center,
				radius: '500',
				//type: ['school','hotel','casino','market']
			};			
			var service = new google.maps.places.PlacesService(map);
			service.nearbySearch(request,function(results, status) {
			  if (status == google.maps.places.PlacesServiceStatus.OK) {
			  	cleanMarkers();

			    for (var i = 0; i < results.length; i++) {
			      //console.log(results[i].geometry.location);
				  setMarker(results[i].geometry.location,i+1,results[i].place_id);
			    }
			    
			    //drawCircle(center,500);
			  }else{

			  	alert('No any location found!');
			  }
			});
		}


		//auto location current city
		function find_city(pos){
			var request = {
				location: center,
				radius: '1000',
			};

			var service = new google.maps.places.PlacesService(map);
			service.nearbySearch(request,function(results, status) {
			  if (status == google.maps.places.PlacesServiceStatus.OK) {
			  	
			    var city=results[0].name;
			    document.getElementById('init_city').innerText = city?city:'';
			    //drawCircle(center,500);
			  }else{

			  	alert('Sorry,you are in an unknow place!');
			  }
			});
		}


		/*路线规划
		directionsService的返回值status如下:
		1.OK 表示响应中包含有效的 DirectionsResult。
		2.NOT_FOUND 表示请求的出发地、目的地或航点中指定的位置中至少有一个无法接受地理编码。
		3.ZERO_RESULTS 表示在出发地和目的地之间找不到路线。
		4.MAX_WAYPOINTS_EXCEEDED 表示 DirectionsRequest 中提供的 DirectionsWaypoint 字段过多。请参阅下文的航点限制部分。
		5.MAX_ROUTE_LENGTH_EXCEEDED 表示所请求的路线过长，无法进行处理。当系统返回更复杂的路线时，就会发生此错误。不妨尝试减少航点、转弯或指示的数量。
		6.INVALID_REQUEST 表示提供的 DirectionsRequest 无效。导致出现此错误代码的最常见原因包括：请求中缺少出发地或目的地；或者公交请求中包含航点。
		7.OVER_QUERY_LIMIT 表示网页在允许的时间段内发送的请求过多。
		8.REQUEST_DENIED 表示不允许网页使用路线服务。
		9.UNKNOWN_ERROR 表示因服务器错误而无法处理路线请求。如果您重试，请求可能会成功。
		*/

		calcRouteButton.addEventListener('click',calcRoute);
		function calcRoute(){
		  var start = document.getElementById('pos1').value;
		  var end = document.getElementById('pos2').value;
		  if(!start || !end) {return;}

		  start=JSON.parse(start);
		  end=JSON.parse(end);

		  var request = {
		    origin: start,
		    destination: end,
		    travelMode: 'DRIVING'
		  };
		  directionsService.route(request, function(result, status) {
		    if (status == 'OK') {
				directionsRenderer.setDirections(result);

				var leg = result.routes[0].legs[0];

				route_obj.address_start = leg.start_address;
				route_obj.address_end = leg.end_address;
				route_obj.distance = leg.distance.text;
				route_obj.distance_value = (leg.distance.value*1/1000).toFixed(2);
				route_obj.duration = leg.duration;
				console.log(route_obj);

				var routeInfo ="<div style='color:#00F'>起点:"+leg.start_address+"</div>";
				routeInfo +="<div style='color:#0F0'>终点:"+leg.end_address+"</div>";
				routeInfo +="<div>距离:"+leg.distance.text+"</div>";
				routeInfo +="<div>预计时间:"+leg.duration.text+"</div>";

				setInfo(center,routeInfo,map);

		    }else{
		    	console.log(status);
		    }
		  });
		}		

		//建立信息窗口
		function setInfo(pos,text,map){
			infoWindow.setMap(null);
			infoWindow=null;
			infoWindow = new google.maps.InfoWindow({content:text});
			infoWindow.setPosition(pos); //建立一个info
			infoWindow.open(map); //info放进地图上
			//map.setCenter(pos);  //地图中心移动到pos上
		}


		function getDetailInfo(pos){

			//查出图标的详细资料
			var service = new google.maps.places.PlacesService(map);	
			var request = {
				placeId:'xx',
				location:pos
			};

			service.getDetails(request,function(result,status){
				if(status=='OK'){
					console.log({status:status,result:result});
					var infoTxt = "<div style='font-weight:bold;color:blue;'>"+result.name+"</div><div>"+result.formatted_address+"</div>";
						infoTxt+="<div style='border-top:1px solid #ccc;'><a style='color:blue;' href='"+result.url+"'>Google for this place</a></div>";
					setInfo(pos,infoTxt,map);
					
					calcRoute();

				}else{
					alert('From google:['+status+']');
				}

			});
		}



		whereIsHere();
		outTextQuery = textQuery;
		outCalcRoute = calcRoute;
		outSetMarker = setMarker;
		
	}

	window.onload = loadScript;
	
	$(document).ready(function(){

		$("#to_home").css({'background':"#f90"});

		function truck_pos() {
			console.log(current_pos);
			//console.log($("#init_city").text());
			if($("#is_driver").val() && current_pos){
				$.post('/index.php/order/set_driver_pos',{driver_pos:current_pos,current_city:$("#init_city").text()},function(res){
					var res =JSON.parse(res);
				    console.log(res);
				});
			}else{
				console.log('Normal customer!');
			}
		};
		truck_pos();
		setInterval(truck_pos, 30*1000);
		

		//附近的车子
		function trucks_near(){
			if(!$("#init_city").text()) {
				console.log('You are in an unknow place');
				return;
			}
			const image ="/upload/truck2.png";
			$.post('/index.php/truck/trucks_near',{city:$("#init_city").text()},function(res){
				var res = JSON.parse(res);
				var data = res.data;
				//console.log(data);

			    for (var i = 0; i < data.length; i++) {
			      console.log('Truck:'+data[i].p);
				  outSetMarker(JSON.parse(data[i].p),'','',image);
			    }	
			    $("#from").trigger('click');
			})
		}
		

		$("#trucks_near").on('click',function(){
			trucks_near();
		}); 
		$("#address_search").on('click',function(){
			outTextQuery($("#address_input").val().trim());
		});	;


		var msg=$("#show_msg").val().trim();
		var msg2=$("#pwd_msg").val().trim();

	    $("#want_time").flatpickr({
	        enableTime: true,
	        //dateFormat: "Y-m-d H:i",
	    });


		// if(msg || msg2){
		// 	layer.open({
		// 		title:'System message',
		// 		content:msg+"<br/>"+msg2
		// 	})
		// }


		//地址编辑//////
		var addr_edit =1;
		$("#address1").on('click',function(){
			var addr_text =$(this).text().split("❖");
			$("#addr_cont").val('');
			$("#addr_mobile").val('');			
			if(addr_text[0]) $("#addr_text").val(addr_text[0].trim());
			if(addr_text[1]) $("#addr_cont").val(addr_text[1].trim());
			if(addr_text[2]) $("#addr_mobile").val(addr_text[2].trim());
			$("#addr_editor").show();
			$("#mask").show();
			addr_edit=1;
		})

		$("#address2").on('click',function(){
			var addr_text =$(this).text().split("❖");
			$("#addr_cont").val('');
			$("#addr_mobile").val('');
			if(addr_text[0]) $("#addr_text").val(addr_text[0].trim());
			if(addr_text[1]) $("#addr_cont").val(addr_text[1].trim());
			if(addr_text[2]) $("#addr_mobile").val(addr_text[2].trim());
			$("#addr_editor").show();
			$("#mask").show();
			addr_edit=2;
		})		
		$("#edit_close").on('click',function(){
			$("#addr_editor").hide();
			$("#mask").hide();
		
		})		
		$("#addr_save").on('click',function(){
			$("#addr_editor").hide();
			$("#mask").hide();
			var address_text ='';
			if($("#addr_text").val()) address_text+=$("#addr_text").val();
			if($("#addr_cont").val()) address_text+=("❖"+$("#addr_cont").val());
			if($("#addr_mobile").val()) address_text+=("❖"+$("#addr_mobile").val());

			$("#address"+addr_edit).text(address_text);
		})
		//地址编辑//////


		//保存地址到地址簿
		$("#addr_save_book").on('click',function(e) {
			var addr = $("#addr_text").val();
			var cont = $("#addr_cont").val();
			var mobile = $("#addr_mobile").val();
			var pos = $("#pos1").val();

			if(!addr.trim() || !cont.trim() || !mobile.trim()){
				layer.msg('请输入完整的联系地址，联系人资料！');return false;
			}

			var data={id:$("#addr_id").val(),addr:addr,cont:cont,mobile:mobile,pos:pos};
		    layer.confirm('是否确认保存地址?', {
		      btn: ['Yes','No'] //按钮
		    }, function(){
		    	//submit 
				$.post('/index.php/customer/address_edit',data,function(res){
					var res =JSON.parse(res);
					layer.msg(res.msg);
				})  

		    }, function(){
		    	 layer.msg('yes!');
		    });

		})


		//货车选择
		$(".btn-cat").on('click',function(){
			var cat = $(this).attr('cat');
			$(".btn-cat").removeClass('cat_selected');
			$(this).addClass('cat_selected');

			//货车类别资料显示
			$('.cat_info').hide().each(function(){
				if($(this).attr('cat')==cat){
					$(this).show();
					base_distance = $(this).find('.base_distance').text()*1;
					price_per_km =$(this).find('.price_per_km').text()*1;
					base_price = $(this).find('.base_price').text()*1;
				}
			})
			layer.msg("已选择车型【"+$(this).text()+"】.");
			$("#cat_name").text($(this).text());


			$("#address_get").trigger('click');
		})


		$(".btn-cat:first-child").trigger('click');
		$(".bi-arrow-clockwise").on('click',function(){
			window.location.reload();

		})

		$(".bi-app").on('click',function(){
			layer.open({
				title:'App download',
				content:"<img src='/upload/down.png' style='width:100%;border:3px solid #111;border-radius:6px;' />",
			})
		})


		//打开地址本
		$("#book1,#book2").on('click',function(){
			if($(this).attr('id')=='book1') a_find=1;
			if($(this).attr('id')=='book2') a_find=2;
			//$(this).animate({'fontSize':'1.2rem'}).animate({'fontSize':'1rem'});

			$.post('/index.php/customer/my_address',{},function(res){
				var res =JSON.parse(res);
				if(res.code){
					var list = res.list;
					var add_module = $("#add_module").html();
					$("#address_list").html('<div style="padding:5px 10px;">My address</div>');
					list.forEach(function(item,index,self){
						//console.log(item);
						new_html =add_module.replace('[addr]',item.address);
						new_html =new_html.replace('[cont]',item.contact);
						new_html =new_html.replace('[mobi]',item.mobile);
						new_html =new_html.replace('[pos]',item.pos);
						$("#address_list").append(new_html);
					});
					$("#mask").show();
					$("#address_list").show();

				}else{
					layer.msg(res.msg);
				}
			})
		})

		$("#mask").on('click',function(){
			$(this).hide();
			$("#address_list").hide();
			$("#container").hide();
			$("#addr_editor").hide();
		})

		//选地址
		$("#address_list").on('click','.address',function(){
			$(".add_check").hide();
			$(this).find('.add_check').show();
			var addr = $(this).find('.addr').text();
			var cont = $(this).find('.cont').text();
			var mobi = $(this).find('.mobi').text();
			var pos = $(this).find('.pos').text();

			if(pos.length<10){
				layer.open({content:"此地址没有定位信息，请到地址本中修改！"});return;
			}

			addr =addr+"❖"+cont+"❖"+mobi;
			$("#address"+a_find).html(addr);
			$("#pos"+a_find).val(pos);

			if($("#pos1").val() && $("#pos2").val()){
				outCalcRoute();
				setTimeout(function(){
					console.log(route_obj);
					var price=0;
					if(route_obj.distance_value*1<=base_distance){
						price = base_price;
					}else{
						price=base_price+(route_obj.distance_value-base_distance)*price_per_km,2;
						price=price.toFixed(2);
					}

					$("#km").text(route_obj.distance_value);
					$("#price").text(price);
				},1000);

				$("#mask").show();
			}
		})

		//打开地图
		$("#from,#to").on('click',function(){
			$("#address_input").val('');
			$("#container").show();
			$("#mask").show();
			if($(this).attr('id')=='from') a_find=1;
			if($(this).attr('id')=='to') a_find=2;

			console.log('a_find:'+a_find);
		})



		//地图上选择地址
		$("#address_get").on('click',function(){

			if($("#address_input").val()){
				$("#address"+a_find).text($("#address_input").val());
			}

			//两个地址都选择好，显示距离，价格
			if($('#pos1').val() && $("#pos2").val()){
				var price=0;
				if(route_obj.distance_value*1<=base_distance){
					price = base_price;
				}else{
					price=base_price+(route_obj.distance_value-base_distance)*price_per_km,2;
					price=price.toFixed(2);
				}

				$("#km").text(route_obj.distance_value);
				$("#price").text(price);
			}

			$("#mask").hide();
			$("#container").hide();

		})

		//下单
		$("#place_order").on('click',function(){
			var address1 = $("#address1").text().trim();
			var address2 = $("#address2").text().trim();
			var pos1 = $("#pos1").val().trim();
			var pos2 = $("#pos2").val().trim();

			var want_time = $("#want_time").val();
			var cat_selected = $(".cat_selected").attr('cat');
			var km=$("#km").text();
			var price = $("#price").text();
			if(isNaN(km) || isNaN(price)) {
				layer.msg("【距离】或者【价格】不正确，请重新选择地址！");return;
			}

			if(!address2 || !address1){
				layer.msg("请选择【装货地址】和【卸货地址】！");return;
			}


			if(address1.indexOf('❖')<0 ){
				layer.msg("请设置发货地【联系人】及【手机号码】！");return;
			}
			if(address2.indexOf('❖')<0){
				layer.msg("请设置收货地【联系人】及【手机号码】！");return;
			}			
			if(!pos1 || !pos2){
				layer.msg("请设置地址【坐标】以规划路线！");return;
			}			

			if(!cat_selected){
				layer.msg("请选择【货车类型】！");return;
			}

			


			//询问框
			var confirm_msg="<div>";
				confirm_msg +="<div>装货:"+address1+"</div>";
				confirm_msg +="<div>卸货:"+address2+"</div>";
				confirm_msg +="<div>总里程:"+km+"km,订单价格:$"+price+"</div>";
				confirm_msg +="<div style='color:blue;'>是否确定提交订单?</div></div>";
		    layer.confirm(confirm_msg, {
		      btn: ['Yes','No'] //按钮
		    }, function(){
		    	//submit order
				$.post('/index.php/order/add',{
					split:'❖',
					cat:cat_selected,
					addr1:address1,
					addr2:address2,
					pos1:pos1,
					pos2:pos2,
					km:km,
					price:price,
					want_time:want_time
				},function(res){
					var res =JSON.parse(res);
					console.log(res.msg);
					layer.msg(res.msg);

				})  

		    }, function(){
		    	// layer.msg('yes!');
		     	//	return false;
		    });




		});

	});
</script>
</body>
</html>